package mobao.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;

/**
 * Created by yanghongquan on 2018/8/13 17:08
 */
public class moboDemoFilter extends ZuulFilter{
    /**
     * 返回哪个生命周期中进行执行
     * pre-请求前调用,routing-请求时调用,post-在routing和error后调用,error-请求错误时进行调用...
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 一个阶段多个过滤器时,按返回值的顺序进行执行
     * 数字越小优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断该过滤器是否需要执行...逻辑部分...
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("API网关的pre过滤器-"+ LocalDate.now());
        RequestContext cts = RequestContext.getCurrentContext();
        HttpServletRequest request = cts.getRequest();

        Object accessToken = request.getParameter("token");
        if(accessToken != null){//测试传入值token就拦截住
            System.out.println("token我不需要,你还想进来?");
            cts.setSendZuulResponse(false);
            cts.setResponseStatusCode(401);
            return null;
        }
        return null;
    }
}
